package com.ym.producer.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class TestService {
    @Qualifier("taskExecutor")
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 这里必须指定任务调度器，避免使用默认调度器
     */
    @Async("taskExecutor")
    public void testAsync(){
        try {
            log.info("即将开始休眠");
            log.info(Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(5);
            log.info("休眠结束......"+ Timestamp.valueOf(LocalDateTime.now()));
        } catch (InterruptedException e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 无需使用@Async注解
     * 这里必须指定任务调度器，避免使用默认调度器
     * @return
     */
    public CompletableFuture<String> testAsync2(){
        return CompletableFuture.supplyAsync(() -> {
            try {
                log.info("即将开始休眠");
                log.info(Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(5);
                log.info("休眠结束......"+ Timestamp.valueOf(LocalDateTime.now()));
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
            return "这是我测试的数据";
        },taskExecutor);
    }

    public void testMQ(){
        try {
            rabbitTemplate.convertAndSend("queueTest","hello,rabbit");
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
